package com.pointcircle.estate.server.framework.repository;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pointcircle.core.IRepository;
import com.pointcircle.core.entity.User;
import com.pointcircle.estate.server.framework.entity.QualityMeasureCheckQualityCc;
import com.pointcircle.estate.server.framework.entity.QualityMeasureCheckQualityProblem;

@Repository
public interface QualityMeasureCheckQualityCcRepository extends IRepository<QualityMeasureCheckQualityCc, String> {
	
	List<QualityMeasureCheckQualityCc> findByQualityMeasureCheckQualityProblem(QualityMeasureCheckQualityProblem qualityMeasureCheckQualityProblem);

	@Query("select o from QualityMeasureCheckQualityCc o where o.cc = :cc and DATE(o.qualityMeasureCheckQualityProblem.registDate) > DATE(:showDate)")
	List<QualityMeasureCheckQualityCc> findByCcAndDate(@Param("cc") User cc,@Param("showDate") Date newDateToShow);
	
	
	@Query(value = "select t.cc from tb_quality_measure_checkquality_cc t " + 
			"where t.quality_measure_checkquality_problem_id = ?1 ", nativeQuery = true)
	List<String> findCcIdsByQualityMeasureCheckQualityProblemId(String problemId);
	
	@Query(value = "select * from tb_quality_measure_checkquality_cc t " + 
			"where t.cc = ?1 " + 
			"and t.quality_measure_checkquality_problem_id in ( " + 
			"select quality_measure_checkquality_problem_id " + 
			"from tb_quality_measure_checkquality_problem t " + 
			"where t.regist_date > str_to_date(?2, '%Y%m%d') );", nativeQuery = true)
	List<Object> findByCcAndDate(String ccId, String date);

	default List<QualityMeasureCheckQualityCc> findByQualityMeasureCheckQualityProblemIn(
		List<QualityMeasureCheckQualityProblem> qualityMeasureCheckQualityProblems) {
		if(CollectionUtils.isEmpty(qualityMeasureCheckQualityProblems)) {
			return new LinkedList<QualityMeasureCheckQualityCc>();
		}
		return this.findAll(new Specification<QualityMeasureCheckQualityCc>() {
			private static final long serialVersionUID = 1607994814496698422L;

			@Override
			public Predicate toPredicate(Root<QualityMeasureCheckQualityCc> root, CriteriaQuery<?> query,
				CriteriaBuilder cb) {
				query.where(
					root.get("qualityMeasureCheckQualityProblem").in(qualityMeasureCheckQualityProblems)
				);
				return query.getRestriction();
			}
			
		});
	}
}
